import { Injectable, Logger } from '@nestjs/common';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
import { BusinessException } from '@wwjCommon/exception/business.exception';

/**
 * SiteExpireCloseJob - 基于NestJS BullMQ
 * 参考: https://docs.nestjs.com/techniques/queues
 * 对应 Java: @Async + RabbitMQ
 * 对应 PHP: thinkqueue
 */
@Injectable()
export class SiteExpireCloseJob {
  private readonly logger = new Logger(SiteExpireCloseJob.name);

  constructor(@InjectQueue('schedule') private readonly queue: Queue) {}

  /**
   * 添加任务到队列 - 使用BullMQ标准API
   * 参考: https://docs.nestjs.com/techniques/queues#producers
   */
  async addJob(data: any, options?: any) {
    try {
      const job = await this.queue.add('SiteExpireClose', data, options);
      this.logger.log(`SiteExpireClose job added to queue: ${job.id}`, data);
      return job;
    } catch (error) {
      this.logger.error('Failed to add SiteExpireClose job to queue:', error);
      throw new BusinessException('SiteExpireClose任务添加失败');
    }
  }

  /**
   * 处理队列任务
   * 使用Core层基础设施：统一队列服务、异常处理、日志服务
   */
  async processJob(data: any) {
    this.logger.log('SiteExpireClose job processing:', data);

    try {
      // 任务逻辑
      await this.executeJob(data);
      this.logger.log('SiteExpireClose job completed successfully');
    } catch (error) {
      this.logger.error('SiteExpireClose job failed:', error);
      // 使用Core层异常处理
      throw new BusinessException('SiteExpireClose任务处理失败', error);
    }
  }

  /**
   * 执行任务
   * 使用Core层基础设施：日志服务、异常处理
   */
  private async executeJob(data: any) {
    // 实现具体的任务逻辑
    // 例如：
    // - 数据清理
    // - 报表生成
    // - 邮件发送
    // - 数据同步
    // - 备份操作

    this.logger.log('Executing SiteExpireClose job logic with data:', data);

    // 模拟异步操作
    await new Promise((resolve) => setTimeout(resolve, 1000));

    this.logger.log('SiteExpireClose job logic completed');
  }

  /**
   * 手动触发任务
   * 使用Core层基础设施：日志服务、异常处理
   */
  async triggerJob(data?: any) {
    this.logger.log('Manually triggering SiteExpireClose job...');
    try {
      await this.executeJob(data || {});
    } catch (error) {
      this.logger.error('Failed to trigger SiteExpireClose job:', error);
      // 使用Core层异常处理
      throw new BusinessException('SiteExpireClose任务触发失败', error);
    }
  }
}
